<script setup>
import { inject, watchEffect } from 'vue'
const props = defineProps(
  {
    prop: String,
    label: String,
    width: String,
    rules: Array
  },
  
)

const defaultEditActions = {
  addRow: () => {},
  deleteRow: () => {},
  startEditable: () => {},
  cancelEditable: () => {},
  saveEditable: () => {},
}

const editActions = inject('editActions')

const formModel = inject('formModel')

const formProps = inject('formProps')

watchEffect(() => {
  if (props.prop) {
    formProps?.value?.add(props.prop)
  }
})

const getEditModel = (index) => {
  if (!formModel || !formModel.value?.model) {
    return {
      isEditing: false,
      isNew: false,
      formData: {},
      data: {},
    }
  }
  return formModel.value.model[index]
}

const getEditRow = (index)=> getEditModel(index).formData

const isEditing = (index)=> getEditModel(index).isEditing ?? false

const calculateColumnDefaultValue = (scope) => {
  return scope.row?.[props.prop]
};
</script>
<script>
export default {
  name:'EditTableColumn'
}
</script>
<template>
  <el-table-column v-bind="$attrs" :prop="prop" :label="label" :width="width">
    <template #default="scope">
      <el-form-item v-if="isEditing(scope.$index)" :prop="`model.${scope.$index}.formData.${prop}`" :rules="rules">
        <slot
          name="edit"
          :$index="scope.$index"
          :row="getEditRow(scope.$index)"
          :column="scope.column"
          :actions="editActions ?? defaultEditActions"
        >
          {{ calculateColumnDefaultValue(scope) }}
        </slot>
      </el-form-item>
      <slot
        v-else
        :$index="scope.$index"
        :row="scope.row"
        :column="scope.column"
        :actions="editActions ?? defaultEditActions"
      >
        {{ calculateColumnDefaultValue(scope) }}
      </slot>
    </template>
  </el-table-column>
</template>
